<?php



namespace App\Http\Controllers\Backend;


use App\Services\Business\Models\TagCategory;
use App\Zesow\Cache\Impl\TagCategoryCache;
use Illuminate\Http\Request;
use App\Http\Requests\ApiV2\CategoryRequest;

class TagCategoryController extends BaseController
{
    public function index(Request $request)
    {
        $parentId = $request->input("parent_id", 0);
        $data     = TagCategory::query()
            ->with(['children'])
            ->where('parent_id', $parentId)
            ->orderBy('sort')
            ->paginate($request->input('size', 100));
        return $this->successData($data);
    }

    public function tree(TagCategoryCache $tagCategoryCache)
    {
        $companyId =$this->loginCompanyId();
        $categories = $tagCategoryCache->tree($companyId);
        return  $this->successData(compact('categories'));
    }
    function buildMenuTree(array $items, int $parentId = null): array
    {
        $tree = [];
        foreach ($items as $item) {
            if ($item['parent_id'] === $parentId) {
                $children = $this->buildMenuTree($items, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }

        return $tree;
    }
    public function store(CategoryRequest $request, TagCategory $category)
    {
        $data = $request->filldata();
        if (TagCategory::query()->where('name',$data['name'])->exists()) {
            return  $this->error(__('分类名不能有重复'));
        }
       $category->fill($data)->save();
        return $this->success(__('分类添加成功'));

    }

    public function edit($id)
    {
        $category = TagCategory::query()->where('id', $id)->firstOrFail();

        return $this->successData($category);
    }
    public function update(Request $request, $id)
    {

        $title = $request->input('name');
        if (TagCategory::query()->where('name',$title)->where('id', '<>', $id)->exists()){
            return  $this->error(__('分类名不能有重复'));
        }
        $category = TagCategory::query()->where('id', $id)->first();
        $category->update(['name'=>$title]);
        return $this->success(__('更新分类成功'));

    }
    public function updateTitle(Request $request, $id)
    {
        $name = $request->input('name');
        $video = TagCategory::query()->where('id', $id)->firstOrFail();
        $video->update(['name' => $name]);
        return $this->success(__('标题更新成功'));
    }

    public function delete($id)
    {
        $category = TagCategory::find($id);
        if ($category->children()->exists()) {
            return  $this->error(__('存在子分类,无法删除'));
        }

        TagCategory::destroy($id);
        return $this->success(__('标签分类删除成功'));
    }




}
